package com.zziq.cloudpicturebank.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zziq.cloudpicturebank.exception.ErrorCode;
import com.zziq.cloudpicturebank.exception.ThrowUtils;
import com.zziq.cloudpicturebank.model.dto.vipcode.VipCodeBatchAddRequest;
import com.zziq.cloudpicturebank.model.dto.vipcode.VipCodeQueryRequest;
import com.zziq.cloudpicturebank.model.entity.Space;
import com.zziq.cloudpicturebank.model.entity.User;
import com.zziq.cloudpicturebank.model.entity.VipCode;
import com.zziq.cloudpicturebank.model.enums.SvipAndVipEnum;
import com.zziq.cloudpicturebank.service.VipCodeService;
import com.zziq.cloudpicturebank.mapper.VipCodeMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
* @author Mr·张
* @description 针对表【vip_code(会员兑换码表)】的数据库操作Service实现
* @createDate 2025-03-09 14:35:49
*/
@Service
public class VipCodeServiceImpl extends ServiceImpl<VipCodeMapper, VipCode>
    implements VipCodeService{
    @Resource
    private TransactionTemplate transactionTemplate;

    /**
     *获取查询条件
     * @param vipCodeQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<VipCode> getQueryWrapper(VipCodeQueryRequest vipCodeQueryRequest) {
        QueryWrapper<VipCode> queryWrapper = new QueryWrapper<>();
        if (vipCodeQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Integer type = vipCodeQueryRequest.getType();
        Integer status = vipCodeQueryRequest.getStatus();
        Long userId = vipCodeQueryRequest.getUserId();
        Long createdUserId = vipCodeQueryRequest.getCreatedUserId();
        String sortField = vipCodeQueryRequest.getSortField();
        String sortOrder = vipCodeQueryRequest.getSortOrder();
        // 拼接查询条件
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(createdUserId), "createdUserId", createdUserId);
        queryWrapper.eq(ObjUtil.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjUtil.isNotEmpty(type), "type", type);
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 批量添加会员兑换码
     *
     * @param vipCodeBatchAddRequest 批量添加请求
     * @return 操作是否成功
     */
    @Override
    public void batchAddVipCode(VipCodeBatchAddRequest vipCodeBatchAddRequest, User loginUser) {
        Integer type = vipCodeBatchAddRequest.getType();
        if (type == null || (!type.equals(SvipAndVipEnum.SVIP.getValue()) && !type.equals(SvipAndVipEnum.VIP.getValue()))) {
            throw new IllegalArgumentException("类型参数不合法");
        }
        List<VipCode> vipCodeList = new ArrayList<>();
        for (int i = 0; i < vipCodeBatchAddRequest.getCount(); i++) {
            String code = generateUniqueCode();
            VipCode vipCode = new VipCode();
            vipCode.setCode(code);
            vipCode.setType(type);
            vipCode.setStatus(0); // 未使用
            vipCode.setCreatedUserId(loginUser.getId()); // 获取当前管理员ID
            vipCodeList.add(vipCode);
        }
        transactionTemplate.execute(status -> {
            for (VipCode vipCode : vipCodeList) {
                boolean res = save(vipCode);
                ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR, "批量添加会员兑换码失败");
            }
            return true;
        });
    }

    /**
     * 生成唯一的兑换码
     *
     * @return 唯一兑换码
     */
    private String generateUniqueCode() {
        String code;
        do {
            code = generateRandomString(20);
        } while (lambdaQuery().eq(VipCode::getCode, code).count() > 0);

        return code;
    }

    /**
     * 生成随机字符串
     *
     * @param length 字符串长度
     * @return 随机字符串
     */
    private String generateRandomString(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }


}




